package com.op.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.op.entity.RoleMenu;
import com.op.mapper.RoleMenuMapper;
import com.op.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (RoleMenu)表服务实现类
 *
 * @author 孤焰
 * @since 2021-12-27 15:17:04
 */
@Service("roleMenuService")
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Resource
    RoleMenuMapper roleMenuMapper;

    @Override
    public List<Long> checkedMenuIdByRoleId(Long roleId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId, roleId);

        return roleMenuMapper.selectList(lambdaQueryWrapper).stream()
                .map(RoleMenu::getMenuId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindingMenus(Long roleId, List<Long> menuIds) {
        // 先删除再保存
        removeByRoleId(roleId);
        menuIds.forEach(item -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(item);
            roleMenuMapper.insert(roleMenu);
        });
        return true;
    }

    @Override
    public boolean removeByRoleId(Long roleId) {
        LambdaUpdateWrapper<RoleMenu> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(RoleMenu::getRoleId, roleId);
        return roleMenuMapper.delete(lambdaUpdateWrapper) > 0;
    }
}

